﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


using BookStore.Platform.objects;
using System.IO;

using System.Net;
using System.Drawing;
using BookStore.WebAnalyzer;
using System.Xml;
using BookStore.Platform.utils;
namespace BookStore.Platform.apis
{
    public class RanWenChapterApi: ChapterApi
    {
        //htmlunit.WebClient webClient,
        public RanWenChapterApi(IWebAnalyzerApi webAnalyzerApi, IBookApi bookApi, IConvertApi convertApi)
            : base(webAnalyzerApi) 
        {
            this.convertApi = convertApi;
            this.bookApi = bookApi;
        }
        private IConvertApi convertApi = null;
        private IBookApi bookApi = null;
        private static string contentQuery = "content";
        private static string imageQuery = "//div[@class='divimage']";
        private static string titleQuery = "//h1[@class='bname_content']";
        private static string sep = "@";
        private static string chapterUrlQuery = "//div[@class='dccss']";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="baseUrl"></param>
        /// <returns>章节URL， 章节名称</returns>
 
        public override IDictionary<string,string> GetChapterUrls(string url, string baseUrl)
        {
            try
            {
                IDictionary<string,string> chapterUrls = new Dictionary<string,string>();
                XmlDocument doc = webAnalyzerApi.getXmlDocumentFromUrl(url);
                IList<XmlElement> urls = doc.GetNodesByTagAndAttributes("div", "class", "dccss");
                //HtmlPage page = (HtmlPage)WebClient.getPage(url);
                //object[] urls = page.getByXPath(chapterUrlQuery).toArray();
                foreach (XmlElement chapterLink in urls)
                {
                    XmlNode anchor = chapterLink.GetElementsByTagName("a")[0];
                    chapterUrls.Add(baseUrl + "/" + anchor.Attributes["href"].Value, WindowFolderNameCleaner.CleanName(anchor.Attributes["alt"].Value));
                    
                }
                return chapterUrls;
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.StackTrace);
                throw e;
            }
        }

        public override objects.Chapter GetByName(string chapterName, Guid bookId)
        {
            using (BookStore.Platform.data.BookStoreDataContext context = new data.BookStoreDataContext()) 
            {
                var entity = context.t_chapters.FirstOrDefault(x => x.ChapterName.Equals(chapterName) && x.BookId == bookId);
                if (entity == null)
                    return null;
                else
                    return convertApi.convertEntityToBiz(entity);
            }
        }

        public override objects.Chapter GetChapterByUrl(string url, string chapterName,Guid bookId)
        {
            try
            {
                //HtmlPage page = (HtmlPage)WebClient.getPage(url);
                //HtmlDivision contentDiv = (HtmlDivision)(page.getElementById(contentQuery));                
                //string chapterName = ((HtmlElement)page.getByXPath(titleQuery).get(0)).getTextContent();
                XmlDocument doc = webAnalyzerApi.getXmlDocumentFromUrl(url);
                XmlElement contentDiv = doc.GetNodesByTagAndAttributes("div", "id", "content")[0];
                ChapterType chapterType = ChapterType.html;
                string chapterContent = string.Empty;
                IList<XmlElement> imgDivs = contentDiv.getElementsByTagAndAttribute("div", "class", "divimage");
                if (imgDivs.Count > 0)
                {
                    chapterType = ChapterType.img;
                    foreach (XmlNode ele in imgDivs)
                    {
                        string imgSrc = ele.SelectSingleNode("img[@class='imagecontent']").Attributes["src"].Value;
                        chapterContent += imgSrc + sep;
                    }
                    //foreach (HtmlElement ele in contentDiv.getByXPath(imageQuery).toArray())
                    //{
                    //    chapterContent += ((HtmlElement)ele.getByXPath("//img[@class='imagecontent']").get(0)).getAttribute("src") + sep;
                    //}
                }
                else
                {
                    chapterType = ChapterType.txt;
                    chapterContent = contentDiv.InnerText;
                }
                Chapter chapter = new Chapter() 
                {
                    BookId = bookId,
                    ChapterContent = chapterContent,
                    ChapterType = chapterType,
                    ChapterName = chapterName,
                    Created = DateTime.Now,
                    Updated = DateTime.Now
                };
                chapter.Folder = bookApi.GetById(bookId).Folder + "\\" + chapterName;

                return chapter;
            }
            catch (Exception e)
            {
                throw e;
            }

        }

        public override void Save(objects.Chapter chapter)
        {
            using (BookStore.Platform.data.BookStoreDataContext context = new data.BookStoreDataContext()) 
            {
                var entity = context.t_chapters.FirstOrDefault(x => x.ChapterName.Equals(chapter.ChapterName) && x.BookId == chapter.BookId);
                if (entity == null)
                    context.t_chapters.InsertOnSubmit(convertApi.convertBizToEntity(chapter));
                else
                {
                    entity.ChapterContent = chapter.ChapterContent;
                    entity.Updated = DateTime.Now;
                }
                context.SubmitChanges();

                entity = context.t_chapters.FirstOrDefault(x => x.ChapterName.Equals(chapter.ChapterName) && x.BookId == chapter.BookId);
                //get book folder
                if (!Directory.Exists(entity.Folder))
                {
                    Directory.CreateDirectory(entity.Folder);

                    if (entity.ChapterType == ChapterType.txt)
                    {
                        using (StreamWriter sw = new StreamWriter(entity.Folder + "\\" + entity.ChapterName + ".txt"))
                        {
                            sw.Write(entity.ChapterContent);
                            sw.Flush();
                            sw.Close();
                        }
                    }
                    else if (entity.ChapterType == ChapterType.img)
                    {
                        string content = entity.ChapterContent;
                        string [] imgUrls = content.Split(new string [] {sep},StringSplitOptions.None);
                        foreach (string imgUrl in imgUrls)
                        {
                            Image tmp = null;
                            if (!string.IsNullOrEmpty(imgUrl))
                            {
                                HttpWebRequest req = System.Net.WebRequest.Create(imgUrl) as HttpWebRequest;
                                req.Timeout = int.MaxValue;
                                req.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
                                req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)";
                                HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
                                tmp = Image.FromStream(resp.GetResponseStream());
                                tmp.Save(entity.Folder + "\\" + imgUrl.Substring(imgUrl.LastIndexOf("/")));
                            }
                        }
                    }
                }
                //save to disk
            }
        }
    }
}
